package me.lcc.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 演示账号配置和权限配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
	 @Override
	 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		 // 5.x 需要提供一个密码编码实现类
		 // 也可以使用Spring自带的实现类，例如：BCryptPasswordEncoder
		 auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
		 	.withUser("admin").password("1").roles("ADMIN", "USER").and()
		 	.withUser("user").password("2").roles("USER");
	 }
	 
	 @Override
	 protected void configure(HttpSecurity http) throws Exception {
		 http.authorizeRequests()
		    // 无需登陆
		 	.antMatchers("/hello/baby").permitAll() 
		 	// 需要登陆
		 	.antMatchers("/hello/fruit/**").hasRole("USER")
		 	.antMatchers("/hello/animal/**").hasRole("ADMIN")
		 	// 其他只要登陆认证过都可通过
		 	.anyRequest().authenticated().and().formLogin().and().httpBasic();
	 }
	 
	 /**
	  * 密码编码实现类使用明文<br>
	  * 5.x 需要提供一个密码编码实现类
	  */
	 public static class MyPasswordEncoder implements PasswordEncoder {

	    @Override
	    public String encode(CharSequence charSequence) {
	        return charSequence.toString();
	    }

	    @Override
	    public boolean matches(CharSequence charSequence, String s) {
	        return s.equals(charSequence.toString());
	    }
	}
}